<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta name="baidu-site-verification" content="UqlC4pwKIm" />
  <meta name="baidu-site-verification" content="d3U0dGeqGw" />
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="1C1XSuJ8TgM2O0mcZvsgzEdy0IdRZOJfxDYPyh18U9Q" />














  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.cat.net/css?family=Roboto Slab:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="TX1,USB摄像头,MJPEG," />





  <link rel="alternate" href="/atom.xml" title="WordZzzz" type="application/atom+xml" />






<meta name="description" content="转载请注明作者和出处：http://blog.csdn.net/u011475210 嵌入式平台：NVIDIA Jetson TX1 嵌入式系统：Ubuntu16.04 虚拟机系统：Ubuntu14.04 编者: WordZzzz   写在前面：NVIDIA Jetson TX1开发套件包括一个CSI接口的500W摄像头，其官方多媒体例程基于此摄像头详细介绍了图像采集与编解码的种种操作。整个">
<meta name="keywords" content="TX1,USB摄像头,MJPEG">
<meta property="og:type" content="article">
<meta property="og:title" content="NVIDIA Jetson TX1 系列开发教程之九：USB摄像头MJPEG格式图像采集">
<meta property="og:url" content="http://wordzzzz.gitee.io/2017/10/09/tx-9/index.html">
<meta property="og:site_name" content="WordZzzz">
<meta property="og:description" content="转载请注明作者和出处：http://blog.csdn.net/u011475210 嵌入式平台：NVIDIA Jetson TX1 嵌入式系统：Ubuntu16.04 虚拟机系统：Ubuntu14.04 编者: WordZzzz   写在前面：NVIDIA Jetson TX1开发套件包括一个CSI接口的500W摄像头，其官方多媒体例程基于此摄像头详细介绍了图像采集与编解码的种种操作。整个">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-01-01T07:26:35.409Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="NVIDIA Jetson TX1 系列开发教程之九：USB摄像头MJPEG格式图像采集">
<meta name="twitter:description" content="转载请注明作者和出处：http://blog.csdn.net/u011475210 嵌入式平台：NVIDIA Jetson TX1 嵌入式系统：Ubuntu16.04 虚拟机系统：Ubuntu14.04 编者: WordZzzz   写在前面：NVIDIA Jetson TX1开发套件包括一个CSI接口的500W摄像头，其官方多媒体例程基于此摄像头详细介绍了图像采集与编解码的种种操作。整个">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://wordzzzz.gitee.io/2017/10/09/tx-9/"/>





  <title>NVIDIA Jetson TX1 系列开发教程之九：USB摄像头MJPEG格式图像采集 | WordZzzz</title>
  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-111723881-1', 'auto');
  ga('send', 'pageview');
</script>


  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?38fde15c2737a3b69622e9dd4f67f6f1";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">WordZzzz</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">My Awesome Site</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://wordzzzz.gitee.io/2017/10/09/tx-9/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Word Zzzz">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="WordZzzz">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">NVIDIA Jetson TX1 系列开发教程之九：USB摄像头MJPEG格式图像采集</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-10-09T00:00:00+08:00">
                2017-10-09
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2018-01-01T15:26:35+08:00">
                2018-01-01
              </time>
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/TX1/" itemprop="url" rel="index">
                    <span itemprop="name">TX1</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2017/10/09/tx-9/" class="leancloud_visitors" data-flag-title="NVIDIA Jetson TX1 系列开发教程之九：USB摄像头MJPEG格式图像采集">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3,929
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  22
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <script src="\assets\js\APlayer.min.js"> </script><hr>
<ul>
<li><strong>转载请注明作者和出处：<a href="http://blog.csdn.net/u011475210" target="_blank" rel="noopener">http://blog.csdn.net/u011475210</a></strong></li>
<li><strong>嵌入式平台：NVIDIA Jetson TX1</strong></li>
<li><strong>嵌入式系统：Ubuntu16.04</strong></li>
<li><strong>虚拟机系统：Ubuntu14.04</strong></li>
<li><strong>编者: WordZzzz</strong></li>
</ul>
<hr>
<p><strong><font color="black" size="5" face="仿宋">写在前面：</font></strong><br>NVIDIA Jetson TX1开发套件包括一个CSI接口的500W摄像头，其官方多媒体例程基于此摄像头详细介绍了图像采集与编解码的种种操作。整个多媒体例程是基于gstreamer框架来写的，如果大家只是想把摄像头用起来，大可不必研究gstreamer框架，直接看接口就行。</p>
<p>由于项目需求，考虑到接线问题，我们放弃了CSI接口的摄像头，转而采用USB摄像头。而且最新的官方例程已经给出了基于V4L2的USB摄像头图像采集与编码例程。（12_camera_v4l2_cuda_video_encode）。</p>
<p>本博客将介绍三种在TX1上实现USB摄像头图像采集与显示的方法，分别基于gstreamer、ffmpeg和V4L2来实现USB摄像头的图像实时采集与显示。博主在项目中实现拍照和预览模式切换，最终采用的是V4L2+OpenCV2.4.13的方案，因为博主对V4L2比较熟悉，而对于gstreamer和ffmpeg只接触到了皮毛，对其理解也不是很到位。</p>
<p>注意：博主所用的USB摄像头输出图像格式为mjpeg，所以所有的程序中都是以jpeg为例进行编写的，如果想改成YUYV格式的，只需要改一下format设置，并把相应的解码程序去掉即可。</p>
<p><strong><font color="black" size="5" face="仿宋">一、Gstreamer：</font></strong></p>
<p>博主只是直接把测试好的gstreamer命令行写入到程序中，并不能对数据流做更多的操作，在多次尝试无果后放弃······</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line">/*</span><br><span class="line"> * main.cpp</span><br><span class="line"> *</span><br><span class="line"> *  Created on: May 31, 2017</span><br><span class="line"> *      Author: wordzzzz</span><br><span class="line"> */</span><br><span class="line">#include &lt;stdio.h&gt;</span><br><span class="line">#include &lt;stdlib.h&gt;</span><br><span class="line">#include &lt;string.h&gt;</span><br><span class="line">#include &lt;iostream&gt;</span><br><span class="line">#include &lt;errno.h&gt;</span><br><span class="line"></span><br><span class="line">using namespace std;</span><br><span class="line"></span><br><span class="line">int main(int argc, char **argv)</span><br><span class="line">&#123;</span><br><span class="line">	//花括号内输入测试号的命令行即可</span><br><span class="line">	char cmd_cap[] = &#123;&quot;gst-launch-1.0 v4l2src device= /dev/video1 ! &apos;image/jpeg, width=640, height=480&apos; ! jpegdec ! xvimagesink -e &amp;&quot;&#125;;</span><br><span class="line"></span><br><span class="line">	char *cmdstring = cmd_cap;</span><br><span class="line"></span><br><span class="line">	if(*argv[1] == &apos;1&apos;)</span><br><span class="line">		cmdstring = cmd_cap;</span><br><span class="line"></span><br><span class="line">	int status;</span><br><span class="line">	if(NULL == cmdstring) //如果cmdstring为空趁早闪退吧，尽管system()函数也能处理空指针</span><br><span class="line">	&#123;</span><br><span class="line">		return 0;</span><br><span class="line">	&#125;</span><br><span class="line">	status = system(cmdstring);</span><br><span class="line">	if(status &lt; 0)</span><br><span class="line">	&#123;</span><br><span class="line">		printf(&quot;cmd: %s\t error: %s&quot;, cmdstring, strerror(errno)); // 这里务必要把errno信息输出或</span><br><span class="line">		return 0;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	if(WIFEXITED(status))</span><br><span class="line">	&#123;</span><br><span class="line">		printf(&quot;normal termination, exit status = %d\n&quot;, WEXITSTATUS(status)); //取得cmdstring执行结果</span><br><span class="line">	&#125;</span><br><span class="line">		else if(WIFSIGNALED(status))</span><br><span class="line">	&#123;</span><br><span class="line">		printf(&quot;abnormal termination,signal number =%d\n&quot;, WTERMSIG(status)); //如果cmdstring被信号中断，取得信号值</span><br><span class="line">	&#125;</span><br><span class="line">	else if(WIFSTOPPED(status))</span><br><span class="line">	&#123;</span><br><span class="line">		printf(&quot;process stopped, signal number =%d\n&quot;, WSTOPSIG(status)); //如果cmdstring被信号暂停执行，取得信号值</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong><font color="black" size="5" face="仿宋">二、Ffmpeg：</font></strong><br>ffmpeg程序参考雷神博客，并在其基础上进行修改，ffmpeg编解码+SDL多线程定时刷新显示，程序详解还是看雷神的吧，打开传送门：<a href="http://blog.csdn.net/leixiaohua1020/article/details/38868499" target="_blank" rel="noopener">http://blog.csdn.net/leixiaohua1020/article/details/38868499</a></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br></pre></td><td class="code"><pre><span class="line">/*</span><br><span class="line"> * ffm_cap.cpp</span><br><span class="line"> *</span><br><span class="line"> *  Created on: Jul 19, 2017</span><br><span class="line"> *      Author: wordzzzz</span><br><span class="line"> */</span><br><span class="line"></span><br><span class="line">#include &lt;stdio.h&gt;</span><br><span class="line"></span><br><span class="line">#define __STDC_CONSTANT_MACROS</span><br><span class="line"></span><br><span class="line">//Linux...</span><br><span class="line">#ifdef __cplusplus</span><br><span class="line">extern &quot;C&quot;</span><br><span class="line">&#123;</span><br><span class="line">#endif</span><br><span class="line">#include &lt;libavcodec/avcodec.h&gt;</span><br><span class="line">#include &lt;libavformat/avformat.h&gt;</span><br><span class="line">#include &lt;libswscale/swscale.h&gt;</span><br><span class="line">#include &lt;libavdevice/avdevice.h&gt;</span><br><span class="line">#include &lt;SDL/SDL.h&gt;</span><br><span class="line">#ifdef __cplusplus</span><br><span class="line">&#125;;</span><br><span class="line">#endif</span><br><span class="line"></span><br><span class="line">//Output YUV420P</span><br><span class="line">#define OUTPUT_YUV420P 0</span><br><span class="line">//&apos;1&apos; Use Dshow</span><br><span class="line">//&apos;0&apos; Use VFW</span><br><span class="line">#define USE_DSHOW 0</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">//Refresh Event</span><br><span class="line">#define SFM_REFRESH_EVENT  (SDL_USEREVENT + 1)</span><br><span class="line"></span><br><span class="line">#define SFM_BREAK_EVENT  (SDL_USEREVENT + 2)</span><br><span class="line"></span><br><span class="line">int thread_exit=0;</span><br><span class="line"></span><br><span class="line">//SDL线程40ms刷新一次</span><br><span class="line">int sfp_refresh_thread(void *opaque)</span><br><span class="line">&#123;</span><br><span class="line">	thread_exit=0;</span><br><span class="line">	while (!thread_exit) &#123;</span><br><span class="line">		SDL_Event event;</span><br><span class="line">		event.type = SFM_REFRESH_EVENT;</span><br><span class="line">		SDL_PushEvent(&amp;event);</span><br><span class="line">		SDL_Delay(40);</span><br><span class="line">	&#125;</span><br><span class="line">	thread_exit=0;</span><br><span class="line">	//Break</span><br><span class="line">	SDL_Event event;</span><br><span class="line">	event.type = SFM_BREAK_EVENT;</span><br><span class="line">	SDL_PushEvent(&amp;event);</span><br><span class="line"></span><br><span class="line">	return 0;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">int main(int argc, char* argv[])</span><br><span class="line">&#123;</span><br><span class="line"></span><br><span class="line">	AVFormatContext	*pFormatCtx;</span><br><span class="line">	int				i, videoindex;</span><br><span class="line">	AVCodecContext	*pCodecCtx;</span><br><span class="line">	AVCodec			*pCodec;</span><br><span class="line"></span><br><span class="line">	av_register_all();</span><br><span class="line">	avformat_network_init();</span><br><span class="line">	pFormatCtx = avformat_alloc_context();</span><br><span class="line"></span><br><span class="line">	//Open File</span><br><span class="line">	//char filepath[]=&quot;src01_480x272_22.h265&quot;;</span><br><span class="line">	//avformat_open_input(&amp;pFormatCtx,filepath,NULL,NULL)</span><br><span class="line"></span><br><span class="line">	//Register Device</span><br><span class="line">	avdevice_register_all();</span><br><span class="line"></span><br><span class="line">    //Linux：参数设置</span><br><span class="line">	AVDictionary* options = NULL;</span><br><span class="line">	av_dict_set(&amp;options, &quot;input_format&quot;, &quot;mjpeg&quot;, 0); //输入格式</span><br><span class="line">	av_dict_set(&amp;options, &quot;framerate&quot;, &quot;30&quot;, 0);       //帧率</span><br><span class="line">	av_dict_set(&amp;options, &quot;video_size&quot;, &quot;1280x720&quot;, 0);//图像像素</span><br><span class="line">	AVInputFormat *ifmt=av_find_input_format(&quot;video4linux2&quot;);</span><br><span class="line">	if(avformat_open_input(&amp;pFormatCtx,&quot;/dev/video1&quot;,ifmt,&amp;options)!=0)&#123;</span><br><span class="line">		printf(&quot;Couldn&apos;t open input stream.\n&quot;);</span><br><span class="line">		return -1;</span><br><span class="line">	&#125;</span><br><span class="line">	av_dict_free(&amp;options);</span><br><span class="line"></span><br><span class="line">	if(avformat_find_stream_info(pFormatCtx,NULL)&lt;0)</span><br><span class="line">	&#123;</span><br><span class="line">		printf(&quot;Couldn&apos;t find stream information.\n&quot;);</span><br><span class="line">		return -1;</span><br><span class="line">	&#125;</span><br><span class="line">	videoindex=-1;</span><br><span class="line">	for(i=0; i&lt;pFormatCtx-&gt;nb_streams; i++)</span><br><span class="line">		if(pFormatCtx-&gt;streams[i]-&gt;codec-&gt;codec_type==AVMEDIA_TYPE_VIDEO)</span><br><span class="line">		&#123;</span><br><span class="line">			videoindex=i;</span><br><span class="line">			break;</span><br><span class="line">		&#125;</span><br><span class="line">	if(videoindex==-1)</span><br><span class="line">	&#123;</span><br><span class="line">		printf(&quot;Couldn&apos;t find a video stream.\n&quot;);</span><br><span class="line">		return -1;</span><br><span class="line">	&#125;</span><br><span class="line">	pCodecCtx=pFormatCtx-&gt;streams[videoindex]-&gt;codec;</span><br><span class="line">	pCodec=avcodec_find_decoder(pCodecCtx-&gt;codec_id);</span><br><span class="line">	if(pCodec==NULL)</span><br><span class="line">	&#123;</span><br><span class="line">		printf(&quot;Codec not found.\n&quot;);</span><br><span class="line">		return -1;</span><br><span class="line">	&#125;</span><br><span class="line">	if(avcodec_open2(pCodecCtx, pCodec,NULL)&lt;0)</span><br><span class="line">	&#123;</span><br><span class="line">		printf(&quot;Could not open codec.\n&quot;);</span><br><span class="line">		return -1;</span><br><span class="line">	&#125;</span><br><span class="line">	printf(&quot;pCodecCtx-&gt;codec_id %d\n&quot;, pCodecCtx-&gt;codec_id);</span><br><span class="line">	printf(&quot;pCodecCtx-&gt;width %d\n&quot;, pCodecCtx-&gt;width);</span><br><span class="line">	printf(&quot;pCodecCtx-&gt;height %d\n&quot;, pCodecCtx-&gt;height);</span><br><span class="line">	printf(&quot;pCodecCtx-&gt;pix_fmt %d\n&quot;, pCodecCtx-&gt;pix_fmt);</span><br><span class="line">	AVFrame	*pFrame,*pFrameYUV;</span><br><span class="line">	pFrame=av_frame_alloc();</span><br><span class="line">	pFrameYUV=av_frame_alloc();</span><br><span class="line">	//unsigned char *out_buffer=(unsigned char *)av_malloc(avpicture_get_size(AV_PIX_FMT_YUV420P, pCodecCtx-&gt;width, pCodecCtx-&gt;height));</span><br><span class="line">	//avpicture_fill((AVPicture *)pFrameYUV, out_buffer, AV_PIX_FMT_YUV420P, pCodecCtx-&gt;width, pCodecCtx-&gt;height);</span><br><span class="line">	//SDL----------------------------</span><br><span class="line">	if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) &#123;</span><br><span class="line">		printf( &quot;Could not initialize SDL - %s\n&quot;, SDL_GetError());</span><br><span class="line">		return -1;</span><br><span class="line">	&#125;</span><br><span class="line">	int screen_w=0,screen_h=0;</span><br><span class="line">	SDL_Surface *screen;</span><br><span class="line">	screen_w = pCodecCtx-&gt;width;</span><br><span class="line">	screen_h = pCodecCtx-&gt;height;</span><br><span class="line">	screen = SDL_SetVideoMode(screen_w, screen_h, 0,0);</span><br><span class="line"></span><br><span class="line">	if(!screen) &#123;</span><br><span class="line">		printf(&quot;SDL: could not set video mode - exiting:%s\n&quot;,SDL_GetError());</span><br><span class="line">		return -1;</span><br><span class="line">	&#125;</span><br><span class="line">	SDL_Overlay *bmp;</span><br><span class="line">	bmp = SDL_CreateYUVOverlay(pCodecCtx-&gt;width, pCodecCtx-&gt;height,SDL_YV12_OVERLAY, screen);</span><br><span class="line">	SDL_Rect rect;</span><br><span class="line">	rect.x = 0;</span><br><span class="line">	rect.y = 0;</span><br><span class="line">	rect.w = screen_w;</span><br><span class="line">	rect.h = screen_h;</span><br><span class="line">	//SDL End------------------------</span><br><span class="line">	int ret, got_picture;</span><br><span class="line"></span><br><span class="line">	AVPacket *packet=(AVPacket *)av_malloc(sizeof(AVPacket));</span><br><span class="line"></span><br><span class="line">#if OUTPUT_YUV420P</span><br><span class="line">    FILE *fp_yuv=fopen(&quot;output.yuv&quot;,&quot;wb+&quot;);</span><br><span class="line">#endif</span><br><span class="line"></span><br><span class="line">	struct SwsContext *img_convert_ctx;</span><br><span class="line">	img_convert_ctx = sws_getContext(pCodecCtx-&gt;width, pCodecCtx-&gt;height, pCodecCtx-&gt;pix_fmt, pCodecCtx-&gt;width, pCodecCtx-&gt;height, AV_PIX_FMT_YUVJ420P, SWS_BICUBIC, NULL, NULL, NULL);</span><br><span class="line">	//------------------------------</span><br><span class="line">	SDL_Thread *video_tid = SDL_CreateThread(sfp_refresh_thread,NULL);</span><br><span class="line">	//</span><br><span class="line">	SDL_WM_SetCaption(&quot;Simplest FFmpeg Read Camera&quot;,NULL);</span><br><span class="line">	//Event Loop</span><br><span class="line">	SDL_Event event;</span><br><span class="line"></span><br><span class="line">	for (;;) &#123;</span><br><span class="line">		//Wait</span><br><span class="line">		SDL_WaitEvent(&amp;event);</span><br><span class="line">		if(event.type==SFM_REFRESH_EVENT)&#123;</span><br><span class="line">			//------------------------------</span><br><span class="line">			if(av_read_frame(pFormatCtx, packet)&gt;=0)&#123;</span><br><span class="line">				printf(&quot;packet-&gt;stream_index = %d\n&quot;, packet-&gt;stream_index);</span><br><span class="line">				if(packet-&gt;stream_index==videoindex)&#123;</span><br><span class="line">					printf(&quot;videoindex = %d\n&quot;, videoindex);</span><br><span class="line">					ret = avcodec_decode_video2(pCodecCtx, pFrame, &amp;got_picture, packet);</span><br><span class="line">					if(ret &lt; 0)&#123;</span><br><span class="line">						printf(&quot;Decode Error.\n&quot;);</span><br><span class="line">						return -1;</span><br><span class="line">					&#125;</span><br><span class="line">					if(got_picture)&#123;</span><br><span class="line">						SDL_LockYUVOverlay(bmp);</span><br><span class="line">						pFrameYUV-&gt;data[0]=bmp-&gt;pixels[0];</span><br><span class="line">						pFrameYUV-&gt;data[1]=bmp-&gt;pixels[2];</span><br><span class="line">						pFrameYUV-&gt;data[2]=bmp-&gt;pixels[1];</span><br><span class="line">						pFrameYUV-&gt;linesize[0]=bmp-&gt;pitches[0];</span><br><span class="line">						pFrameYUV-&gt;linesize[1]=bmp-&gt;pitches[2];</span><br><span class="line">						pFrameYUV-&gt;linesize[2]=bmp-&gt;pitches[1];</span><br><span class="line">						sws_scale(img_convert_ctx, (const unsigned char* const*)pFrame-&gt;data, pFrame-&gt;linesize, 0, pCodecCtx-&gt;height, pFrameYUV-&gt;data, pFrameYUV-&gt;linesize);</span><br><span class="line"></span><br><span class="line">#if OUTPUT_YUV420P</span><br><span class="line">						int y_size=pCodecCtx-&gt;width*pCodecCtx-&gt;height;</span><br><span class="line">						fwrite(pFrameYUV-&gt;data[0],1,y_size,fp_yuv);    //Y</span><br><span class="line">						fwrite(pFrameYUV-&gt;data[1],1,y_size/4,fp_yuv);  //U</span><br><span class="line">						fwrite(pFrameYUV-&gt;data[2],1,y_size/4,fp_yuv);  //V</span><br><span class="line">#endif</span><br><span class="line"></span><br><span class="line">						SDL_UnlockYUVOverlay(bmp);</span><br><span class="line"></span><br><span class="line">						SDL_DisplayYUVOverlay(bmp, &amp;rect);</span><br><span class="line"></span><br><span class="line">					&#125;</span><br><span class="line">				&#125;</span><br><span class="line">				av_free_packet(packet);</span><br><span class="line">			&#125;else&#123;</span><br><span class="line">				//Exit Thread</span><br><span class="line">				thread_exit=1;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;else if(event.type==SDL_QUIT)&#123;</span><br><span class="line">			thread_exit=1;</span><br><span class="line">		&#125;else if(event.type==SFM_BREAK_EVENT)&#123;</span><br><span class="line">			break;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	sws_freeContext(img_convert_ctx);</span><br><span class="line"></span><br><span class="line">#if OUTPUT_YUV420P</span><br><span class="line">    fclose(fp_yuv);</span><br><span class="line">#endif</span><br><span class="line"></span><br><span class="line">	SDL_Quit();</span><br><span class="line"></span><br><span class="line">	//av_free(out_buffer);</span><br><span class="line">	av_free(pFrameYUV);</span><br><span class="line">	avcodec_close(pCodecCtx);</span><br><span class="line">	avformat_close_input(&amp;pFormatCtx);</span><br><span class="line"></span><br><span class="line">	return 0;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong><font color="black" size="5" face="仿宋">三、V4L2+OpenCV2.4.13：</font></strong></p>
<p>这里贴出自己的代码，其中V4L2各功能函数是按照标准的V4L2框架进行编写的。本篇博客只贴出摄像头图像采集程序代码，下一篇将针对拍照+预览程序进行代码讲解：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">/*</span><br><span class="line"> * include.h</span><br><span class="line"> *</span><br><span class="line"> *  Created on: Jul 26, 2017</span><br><span class="line"> *      Author: wordzzzz</span><br><span class="line"> */</span><br><span class="line"></span><br><span class="line">#ifndef INCLUDE_H_</span><br><span class="line">#define INCLUDE_H_</span><br><span class="line"></span><br><span class="line">extern &quot;C&quot; &#123;</span><br><span class="line">#include &lt;unistd.h&gt;</span><br><span class="line">#include &lt;error.h&gt;</span><br><span class="line">#include &lt;fcntl.h&gt;</span><br><span class="line">#include &lt;pthread.h&gt;</span><br><span class="line">#include &lt;termios.h&gt;</span><br><span class="line">#include &lt;linux/videodev2.h&gt;</span><br><span class="line">#include &lt;sys/mman.h&gt;</span><br><span class="line">#include &lt;sys/time.h&gt;</span><br><span class="line">#include &lt;sys/ioctl.h&gt;</span><br><span class="line">#include &lt;sys/types.h&gt;</span><br><span class="line"></span><br><span class="line">#include &lt;stdio.h&gt;</span><br><span class="line">#include &lt;stdlib.h&gt;</span><br><span class="line">#include &lt;string.h&gt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">#include &lt;iostream&gt;</span><br><span class="line">#include &lt;iomanip&gt;</span><br><span class="line">#include &lt;string&gt;</span><br><span class="line"></span><br><span class="line">#include &lt;opencv2/core/core.hpp&gt;</span><br><span class="line">#include &lt;opencv2/highgui/highgui.hpp&gt;</span><br><span class="line"></span><br><span class="line">using namespace std;</span><br><span class="line"></span><br><span class="line">#endif /* INCLUDE_H_ */</span><br></pre></td></tr></table></figure></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br><span class="line">308</span><br><span class="line">309</span><br><span class="line">310</span><br><span class="line">311</span><br><span class="line">312</span><br><span class="line">313</span><br><span class="line">314</span><br><span class="line">315</span><br><span class="line">316</span><br><span class="line">317</span><br><span class="line">318</span><br><span class="line">319</span><br><span class="line">320</span><br><span class="line">321</span><br><span class="line">322</span><br><span class="line">323</span><br><span class="line">324</span><br><span class="line">325</span><br><span class="line">326</span><br><span class="line">327</span><br><span class="line">328</span><br><span class="line">329</span><br><span class="line">330</span><br><span class="line">331</span><br><span class="line">332</span><br><span class="line">333</span><br><span class="line">334</span><br><span class="line">335</span><br><span class="line">336</span><br><span class="line">337</span><br><span class="line">338</span><br><span class="line">339</span><br><span class="line">340</span><br><span class="line">341</span><br><span class="line">342</span><br><span class="line">343</span><br><span class="line">344</span><br><span class="line">345</span><br><span class="line">346</span><br><span class="line">347</span><br><span class="line">348</span><br><span class="line">349</span><br><span class="line">350</span><br><span class="line">351</span><br><span class="line">352</span><br><span class="line">353</span><br><span class="line">354</span><br><span class="line">355</span><br><span class="line">356</span><br><span class="line">357</span><br><span class="line">358</span><br><span class="line">359</span><br><span class="line">360</span><br><span class="line">361</span><br><span class="line">362</span><br><span class="line">363</span><br><span class="line">364</span><br><span class="line">365</span><br><span class="line">366</span><br><span class="line">367</span><br><span class="line">368</span><br><span class="line">369</span><br><span class="line">370</span><br><span class="line">371</span><br><span class="line">372</span><br><span class="line">373</span><br><span class="line">374</span><br><span class="line">375</span><br><span class="line">376</span><br><span class="line">377</span><br><span class="line">378</span><br><span class="line">379</span><br><span class="line">380</span><br></pre></td><td class="code"><pre><span class="line">/*</span><br><span class="line"> * v4l2cap.cpp</span><br><span class="line"> *</span><br><span class="line"> *  Created on: Jul 26, 2017</span><br><span class="line"> *      Author: wordzzzz</span><br><span class="line"> */</span><br><span class="line"></span><br><span class="line">#include &quot;v4l2cap.h&quot;</span><br><span class="line"></span><br><span class="line">V4L2Capture::V4L2Capture(char *devName, int width, int height, int width_cap, int height_cap) &#123;</span><br><span class="line">	// TODO Auto-generated constructor stub</span><br><span class="line">	this-&gt;devName = devName;</span><br><span class="line">	this-&gt;fd_cam = -1;</span><br><span class="line">	this-&gt;buffers = NULL;</span><br><span class="line">	this-&gt;n_buffers = 0;</span><br><span class="line">	this-&gt;frameIndex = -1;</span><br><span class="line">	this-&gt;width=width;</span><br><span class="line">	this-&gt;height=height;</span><br><span class="line">	this-&gt;widthCap=width_cap;</span><br><span class="line">	this-&gt;heightCap=height_cap;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">V4L2Capture::~V4L2Capture() &#123;</span><br><span class="line">	// TODO Auto-generated destructor stub</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/**********打开设备**********/</span><br><span class="line">int V4L2Capture::openDevice() &#123;</span><br><span class="line">	/*设备的打开*/</span><br><span class="line">	printf(&quot;video dev : %s\n&quot;, devName);</span><br><span class="line">	fd_cam = open(devName, O_RDWR);</span><br><span class="line">	if (fd_cam &lt; 0) &#123;</span><br><span class="line">		perror(&quot;Can&apos;t open video device&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	return TRUE;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/**********关闭设备**********/</span><br><span class="line">int V4L2Capture::closeDevice() &#123;</span><br><span class="line">	if (fd_cam &gt; 0) &#123;</span><br><span class="line">		int ret = 0;</span><br><span class="line">		if ((ret = close(fd_cam)) &lt; 0) &#123;</span><br><span class="line">			perror(&quot;Can&apos;t close video device&quot;);</span><br><span class="line">		&#125;</span><br><span class="line">		return TRUE;</span><br><span class="line">	&#125; else &#123;</span><br><span class="line">		return FALSE;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/**********初始化设备（预览模式）**********/</span><br><span class="line">int V4L2Capture::initDevice() &#123;</span><br><span class="line">	int ret;</span><br><span class="line">	struct v4l2_capability cam_cap;		//显示设备信息</span><br><span class="line">	struct v4l2_cropcap cam_cropcap;	//设置摄像头的捕捉能力</span><br><span class="line">	struct v4l2_fmtdesc cam_fmtdesc;	//查询所有支持的格式：VIDIOC_ENUM_FMT</span><br><span class="line">	struct v4l2_crop cam_crop;		    //图像的缩放</span><br><span class="line">	struct v4l2_format cam_format;		//设置摄像头的视频制式、帧格式等</span><br><span class="line"></span><br><span class="line">	/* 使用IOCTL命令VIDIOC_QUERYCAP，获取摄像头的基本信息*/</span><br><span class="line">	ret = ioctl(fd_cam, VIDIOC_QUERYCAP, &amp;cam_cap);</span><br><span class="line">	if (ret &lt; 0) &#123;</span><br><span class="line">		perror(&quot;Can&apos;t get device information: VIDIOCGCAP&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	printf(</span><br><span class="line">			&quot;Driver Name:%s\nCard Name:%s\nBus info:%s\nDriver Version:%u.%u.%u\n&quot;,</span><br><span class="line">			cam_cap.driver, cam_cap.card, cam_cap.bus_info,</span><br><span class="line">			(cam_cap.version &gt;&gt; 16) &amp; 0XFF, (cam_cap.version &gt;&gt; 8) &amp; 0XFF,</span><br><span class="line">			cam_cap.version &amp; 0XFF);</span><br><span class="line"></span><br><span class="line">	/* 使用IOCTL命令VIDIOC_ENUM_FMT，获取摄像头所有支持的格式*/</span><br><span class="line">	cam_fmtdesc.index = 0;</span><br><span class="line">	cam_fmtdesc.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;</span><br><span class="line">	printf(&quot;Support format:\n&quot;);</span><br><span class="line">	while (ioctl(fd_cam, VIDIOC_ENUM_FMT, &amp;cam_fmtdesc) != -1) &#123;</span><br><span class="line">		printf(&quot;\t%d.%s\n&quot;, cam_fmtdesc.index + 1, cam_fmtdesc.description);</span><br><span class="line">		cam_fmtdesc.index++;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	/* 使用IOCTL命令VIDIOC_CROPCAP，获取摄像头的捕捉能力*/</span><br><span class="line">	cam_cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;</span><br><span class="line">	if (0 == ioctl(fd_cam, VIDIOC_CROPCAP, &amp;cam_cropcap)) &#123;</span><br><span class="line">		printf(&quot;Default rec:\n\tleft:%d\n\ttop:%d\n\twidth:%d\n\theight:%d\n&quot;,</span><br><span class="line">				cam_cropcap.defrect.left, cam_cropcap.defrect.top,</span><br><span class="line">				cam_cropcap.defrect.width, cam_cropcap.defrect.height);</span><br><span class="line">		/* 使用IOCTL命令VIDIOC_S_CROP，获取摄像头的窗口取景参数*/</span><br><span class="line">		cam_crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;</span><br><span class="line">		cam_crop.c = cam_cropcap.defrect;		//默认取景窗口大小</span><br><span class="line">		if (-1 == ioctl(fd_cam, VIDIOC_S_CROP, &amp;cam_crop)) &#123;</span><br><span class="line">			//printf(&quot;Can&apos;t set crop para\n&quot;);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125; else &#123;</span><br><span class="line">		printf(&quot;Can&apos;t set cropcap para\n&quot;);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	/* 使用IOCTL命令VIDIOC_S_FMT，设置摄像头帧信息*/</span><br><span class="line">	cam_format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;</span><br><span class="line">	cam_format.fmt.pix.width = width;</span><br><span class="line">	cam_format.fmt.pix.height = height;</span><br><span class="line">	cam_format.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;		//要和摄像头支持的类型对应</span><br><span class="line">	cam_format.fmt.pix.field = V4L2_FIELD_INTERLACED;</span><br><span class="line">	ret = ioctl(fd_cam, VIDIOC_S_FMT, &amp;cam_format);</span><br><span class="line">	if (ret &lt; 0) &#123;</span><br><span class="line">		perror(&quot;Can&apos;t set frame information&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	/* 使用IOCTL命令VIDIOC_G_FMT，获取摄像头帧信息*/</span><br><span class="line">	cam_format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;</span><br><span class="line">	ret = ioctl(fd_cam, VIDIOC_G_FMT, &amp;cam_format);</span><br><span class="line">	if (ret &lt; 0) &#123;</span><br><span class="line">		perror(&quot;Can&apos;t get frame information&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	printf(&quot;Current data format information:\n\twidth:%d\n\theight:%d\n&quot;,</span><br><span class="line">			cam_format.fmt.pix.width, cam_format.fmt.pix.height);</span><br><span class="line">	return TRUE;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/**********初始化设备（拍照模式）**********/</span><br><span class="line">int V4L2Capture::initDeviceCap() &#123;</span><br><span class="line">	int ret;</span><br><span class="line">	struct v4l2_format cam_format;		//设置摄像头的视频制式、帧格式等</span><br><span class="line"></span><br><span class="line">	/* 使用IOCTL命令VIDIOC_S_FMT，设置摄像头帧信息*/</span><br><span class="line">	cam_format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;</span><br><span class="line">	cam_format.fmt.pix.width = widthCap;</span><br><span class="line">	cam_format.fmt.pix.height = heightCap;</span><br><span class="line">	cam_format.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;		//要和摄像头支持的类型对应</span><br><span class="line">	cam_format.fmt.pix.field = V4L2_FIELD_INTERLACED;</span><br><span class="line">	ret = ioctl(fd_cam, VIDIOC_S_FMT, &amp;cam_format);</span><br><span class="line">	if (ret &lt; 0) &#123;</span><br><span class="line">		perror(&quot;Can&apos;t set frame information&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	/* 使用IOCTL命令VIDIOC_G_FMT，获取摄像头帧信息*/</span><br><span class="line">	cam_format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;</span><br><span class="line">	ret = ioctl(fd_cam, VIDIOC_G_FMT, &amp;cam_format);</span><br><span class="line">	if (ret &lt; 0) &#123;</span><br><span class="line">		perror(&quot;Can&apos;t get frame information&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	printf(&quot;Current data format information:\n\twidth:%d\n\theight:%d\n&quot;,</span><br><span class="line">			cam_format.fmt.pix.width, cam_format.fmt.pix.height);</span><br><span class="line">	return TRUE;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/**********申请缓存**********/</span><br><span class="line">int V4L2Capture::initBuffers() &#123;</span><br><span class="line">	int ret;</span><br><span class="line">	/* 使用IOCTL命令VIDIOC_REQBUFS，申请帧缓冲*/</span><br><span class="line">	struct v4l2_requestbuffers req;</span><br><span class="line">	CLEAR(req);</span><br><span class="line">	req.count = 4;</span><br><span class="line">	req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;</span><br><span class="line">	req.memory = V4L2_MEMORY_MMAP;</span><br><span class="line">	ret = ioctl(fd_cam, VIDIOC_REQBUFS, &amp;req);</span><br><span class="line">	if (ret &lt; 0) &#123;</span><br><span class="line">		perror(&quot;Request frame buffers failed&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	if (req.count &lt; 2) &#123;</span><br><span class="line">		perror(&quot;Request frame buffers while insufficient buffer memory&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	buffers = (struct cam_buffer*) calloc(req.count, sizeof(*buffers));</span><br><span class="line">	if (!buffers) &#123;</span><br><span class="line">		perror(&quot;Out of memory&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	for (n_buffers = 0; n_buffers &lt; req.count; n_buffers++) &#123;</span><br><span class="line">		struct v4l2_buffer buf;</span><br><span class="line">		CLEAR(buf);</span><br><span class="line">		// 查询序号为n_buffers 的缓冲区，得到其起始物理地址和大小</span><br><span class="line">		buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;</span><br><span class="line">		buf.memory = V4L2_MEMORY_MMAP;</span><br><span class="line">		buf.index = n_buffers;</span><br><span class="line">		ret = ioctl(fd_cam, VIDIOC_QUERYBUF, &amp;buf);</span><br><span class="line">		if (ret &lt; 0) &#123;</span><br><span class="line">			printf(&quot;VIDIOC_QUERYBUF %d failed\n&quot;, n_buffers);</span><br><span class="line">			return FALSE;</span><br><span class="line">		&#125;</span><br><span class="line">		buffers[n_buffers].length = buf.length;</span><br><span class="line">		//printf(&quot;buf.length= %d\n&quot;,buf.length);</span><br><span class="line">		// 映射内存</span><br><span class="line">		buffers[n_buffers].start = mmap(</span><br><span class="line">				NULL, // start anywhere</span><br><span class="line">				buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, fd_cam,</span><br><span class="line">				buf.m.offset);</span><br><span class="line">		if (MAP_FAILED == buffers[n_buffers].start) &#123;</span><br><span class="line">			printf(&quot;mmap buffer%d failed\n&quot;, n_buffers);</span><br><span class="line">			return FALSE;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	return TRUE;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/**********释放缓存**********/</span><br><span class="line">int V4L2Capture::freeBuffers() &#123;</span><br><span class="line">	unsigned int i;</span><br><span class="line">	for (i = 0; i &lt; n_buffers; ++i) &#123;</span><br><span class="line">		if (-1 == munmap(buffers[i].start, buffers[i].length)) &#123;</span><br><span class="line">			printf(&quot;munmap buffer%d failed\n&quot;, i);</span><br><span class="line">			return FALSE;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	free(buffers);</span><br><span class="line">	return TRUE;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/**********开始采集**********/</span><br><span class="line">int V4L2Capture::startCapture() &#123;</span><br><span class="line">	unsigned int i;</span><br><span class="line">	for (i = 0; i &lt; n_buffers; i++) &#123;</span><br><span class="line">		struct v4l2_buffer buf;</span><br><span class="line">		CLEAR(buf);</span><br><span class="line">		buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;</span><br><span class="line">		buf.memory = V4L2_MEMORY_MMAP;</span><br><span class="line">		buf.index = i;</span><br><span class="line">		if (-1 == ioctl(fd_cam, VIDIOC_QBUF, &amp;buf)) &#123;</span><br><span class="line">			printf(&quot;VIDIOC_QBUF buffer%d failed\n&quot;, i);</span><br><span class="line">			return FALSE;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	enum v4l2_buf_type type;</span><br><span class="line">	type = V4L2_BUF_TYPE_VIDEO_CAPTURE;</span><br><span class="line">	if (-1 == ioctl(fd_cam, VIDIOC_STREAMON, &amp;type)) &#123;</span><br><span class="line">		printf(&quot;VIDIOC_STREAMON error&quot;);</span><br><span class="line">		return FALSE;</span><br><span class="line">	&#125;</span><br><span class="line">	return TRUE;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">/**********停止采集**********/</span><br><span class="line">int V4L2Capture::stopCapture() &#123;</span><br><span class="line">	enum v4l2_buf_type type;</span><br><span class="line">	type = V4L2_BUF_TYPE_VIDEO_CAPTURE;</span><br><span class="line">	if (-1 == ioctl(fd_cam, VIDIOC_STREAMOFF, &amp;type)) &#123;</span><br><span class="line">		printf(&quot;VIDIOC_STREAMOFF error\n&quot;);</span><br><span class="line">		return FALSE;</span><br><span class="line">	&#125;</span><br><span class="line">	return TRUE;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/**********获取图像**********/</span><br><span class="line">int V4L2Capture::getFrame(void **frame_buf, size_t* len) &#123;</span><br><span class="line">	struct v4l2_buffer queue_buf;</span><br><span class="line">	CLEAR(queue_buf);</span><br><span class="line">	queue_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;</span><br><span class="line">	queue_buf.memory = V4L2_MEMORY_MMAP;</span><br><span class="line">	if (-1 == ioctl(fd_cam, VIDIOC_DQBUF, &amp;queue_buf)) &#123;</span><br><span class="line">		printf(&quot;VIDIOC_DQBUF error\n&quot;);</span><br><span class="line">		return FALSE;</span><br><span class="line">	&#125;</span><br><span class="line">	//printf(&quot;queue_buf.index=%d\n&quot;,queue_buf.index);</span><br><span class="line">	//pthread_rwlock_wrlock(&amp;rwlock);</span><br><span class="line">	*frame_buf = buffers[queue_buf.index].start;</span><br><span class="line">	*len = buffers[queue_buf.index].length;</span><br><span class="line">	frameIndex = queue_buf.index;</span><br><span class="line">	//pthread_rwlock_unlock(&amp;rwlock);</span><br><span class="line">	return TRUE;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/**********返回队列**********/</span><br><span class="line">int V4L2Capture::backFrame() &#123;</span><br><span class="line">	if (frameIndex != -1) &#123;</span><br><span class="line">		struct v4l2_buffer queue_buf;</span><br><span class="line">		CLEAR(queue_buf);</span><br><span class="line">		queue_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;</span><br><span class="line">		queue_buf.memory = V4L2_MEMORY_MMAP;</span><br><span class="line">		queue_buf.index = frameIndex;</span><br><span class="line">		if (-1 == ioctl(fd_cam, VIDIOC_QBUF, &amp;queue_buf)) &#123;</span><br><span class="line">			printf(&quot;VIDIOC_QBUF error\n&quot;);</span><br><span class="line">			return FALSE;</span><br><span class="line">		&#125;</span><br><span class="line">		return TRUE;</span><br><span class="line">	&#125;</span><br><span class="line">	return FALSE;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/**********预览切换至拍照**********/</span><br><span class="line">int V4L2Capture::pre2cap() &#123;</span><br><span class="line">	if(V4L2Capture::stopCapture() == FALSE)&#123;</span><br><span class="line">		printf(&quot;StopCapture fail~~\n&quot;);</span><br><span class="line">		exit(2);</span><br><span class="line">	&#125;</span><br><span class="line">	if(V4L2Capture::freeBuffers() == FALSE)&#123;</span><br><span class="line">		printf(&quot;FreeBuffers fail~~\n&quot;);</span><br><span class="line">		exit(2);</span><br><span class="line">	&#125;</span><br><span class="line">	if(V4L2Capture::closeDevice() == FALSE)&#123;</span><br><span class="line">		printf(&quot;CloseDevice fail~~\n&quot;);</span><br><span class="line">		exit(1);</span><br><span class="line">	&#125;</span><br><span class="line">	if(V4L2Capture::openDevice() == FALSE)&#123;</span><br><span class="line">		printf(&quot;OpenDevice fail~~\n&quot;);</span><br><span class="line">		exit(1);</span><br><span class="line">	&#125;</span><br><span class="line">	if(V4L2Capture::initDeviceCap() == FALSE)&#123;</span><br><span class="line">		printf(&quot;InitDeviceCap fail~~\n&quot;);</span><br><span class="line">		exit(1);</span><br><span class="line">	&#125;</span><br><span class="line">	if(V4L2Capture::initBuffers() == FALSE)&#123;</span><br><span class="line">		printf(&quot;InitBuffers fail~~\n&quot;);</span><br><span class="line">		exit(2);</span><br><span class="line">	&#125;</span><br><span class="line">	if(V4L2Capture::startCapture() == FALSE)&#123;</span><br><span class="line">		printf(&quot;StartCapture fail~~\n&quot;);</span><br><span class="line">		exit(2);</span><br><span class="line">	&#125;</span><br><span class="line">	return TRUE;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/**********拍照切换至预览**********/</span><br><span class="line">int V4L2Capture::cap2pre() &#123;</span><br><span class="line">	if(V4L2Capture::stopCapture() == FALSE)&#123;</span><br><span class="line">		printf(&quot;StopCapture fail~~\n&quot;);</span><br><span class="line">		exit(2);</span><br><span class="line">	&#125;</span><br><span class="line">	if(V4L2Capture::freeBuffers() == FALSE)&#123;</span><br><span class="line">		printf(&quot;FreeBuffers fail~~\n&quot;);</span><br><span class="line">		exit(2);</span><br><span class="line">	&#125;</span><br><span class="line">	if(V4L2Capture::closeDevice() == FALSE)&#123;</span><br><span class="line">		printf(&quot;CloseDevice fail~~\n&quot;);</span><br><span class="line">		exit(1);</span><br><span class="line">	&#125;</span><br><span class="line">	if(V4L2Capture::openDevice() == FALSE)&#123;</span><br><span class="line">		printf(&quot;OpenDevice fail~~\n&quot;);</span><br><span class="line">		exit(1);</span><br><span class="line">	&#125;</span><br><span class="line">	if(V4L2Capture::initDevice() == FALSE)&#123;</span><br><span class="line">		printf(&quot;InitDevice fail~~\n&quot;);</span><br><span class="line">		exit(1);</span><br><span class="line">	&#125;</span><br><span class="line">	if(V4L2Capture::initBuffers() == FALSE)&#123;</span><br><span class="line">		printf(&quot;InitBuffers fail~~\n&quot;);</span><br><span class="line">		exit(2);</span><br><span class="line">	&#125;</span><br><span class="line">	if(V4L2Capture::startCapture() == FALSE)&#123;</span><br><span class="line">		printf(&quot;StartCapture fail~~\n&quot;);</span><br><span class="line">		exit(2);</span><br><span class="line">	&#125;</span><br><span class="line">	return TRUE;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/**********预览开启**********/</span><br><span class="line">int V4L2Capture::preBegin() &#123;</span><br><span class="line">	if(V4L2Capture::openDevice() == FALSE)&#123;</span><br><span class="line">		printf(&quot;OpenDevice fail~~\n&quot;);</span><br><span class="line">		exit(1);</span><br><span class="line">	&#125;</span><br><span class="line">	printf(&quot;first~~\n&quot;);</span><br><span class="line">	if(V4L2Capture::initDevice() == FALSE)&#123;</span><br><span class="line">		printf(&quot;InitDevice fail~~\n&quot;);</span><br><span class="line">		exit(1);</span><br><span class="line">	&#125;</span><br><span class="line">	printf(&quot;second~~\n&quot;);</span><br><span class="line">	if(V4L2Capture::initBuffers() == FALSE)&#123;</span><br><span class="line">		printf(&quot;InitBuffers fail~~\n&quot;);</span><br><span class="line">		exit(2);</span><br><span class="line">	&#125;</span><br><span class="line">	printf(&quot;third~~\n&quot;);</span><br><span class="line">	if(V4L2Capture::startCapture() == FALSE)&#123;</span><br><span class="line">		printf(&quot;StartCapture fail~~\n&quot;);</span><br><span class="line">		exit(2);</span><br><span class="line">	&#125;</span><br><span class="line">	printf(&quot;fourth~~\n&quot;);</span><br><span class="line">	return TRUE;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/**********预览结束**********/</span><br><span class="line">int V4L2Capture::preEnd() &#123;</span><br><span class="line">	if(V4L2Capture::stopCapture() == FALSE)&#123;</span><br><span class="line">		printf(&quot;StopCapture fail~~\n&quot;);</span><br><span class="line">		exit(2);</span><br><span class="line">	&#125;</span><br><span class="line">	if(V4L2Capture::freeBuffers() == FALSE)&#123;</span><br><span class="line">		printf(&quot;FreeBuffers fail~~\n&quot;);</span><br><span class="line">		exit(2);</span><br><span class="line">	&#125;</span><br><span class="line">	if(V4L2Capture::closeDevice() == FALSE)&#123;</span><br><span class="line">		printf(&quot;CloseDevice fail~~\n&quot;);</span><br><span class="line">		exit(1);</span><br><span class="line">	&#125;</span><br><span class="line">	return TRUE;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line">/*</span><br><span class="line"> * v4l2cap.h</span><br><span class="line"> *</span><br><span class="line"> *  Created on: Jul 26, 2017</span><br><span class="line"> *      Author: wordzzzz</span><br><span class="line"> */</span><br><span class="line"></span><br><span class="line">#ifndef V4L2CAP_H_</span><br><span class="line">#define V4L2CAP_H_</span><br><span class="line"></span><br><span class="line">#include &quot;include.h&quot;</span><br><span class="line"></span><br><span class="line">#define CLEAR(x) memset(&amp;(x), 0, sizeof(x))</span><br><span class="line"></span><br><span class="line">#define TRUE 1</span><br><span class="line">#define FALSE 0</span><br><span class="line"></span><br><span class="line">class V4L2Capture &#123;</span><br><span class="line">public:</span><br><span class="line">	V4L2Capture(char *devName, int width, int height, int width_cap, int height_cap);</span><br><span class="line">	virtual ~V4L2Capture();</span><br><span class="line"></span><br><span class="line">	int openDevice();</span><br><span class="line">	int closeDevice();</span><br><span class="line">	int initDevice();</span><br><span class="line">	int initDeviceCap();</span><br><span class="line">	int startCapture();</span><br><span class="line">	int stopCapture();</span><br><span class="line">	int freeBuffers();</span><br><span class="line">	int getFrame(void **,size_t *);</span><br><span class="line">	int backFrame();</span><br><span class="line">	int pre2cap();</span><br><span class="line">	int cap2pre();</span><br><span class="line">	int preBegin();</span><br><span class="line">	int preEnd();</span><br><span class="line"></span><br><span class="line">	int initBuffers();</span><br><span class="line"></span><br><span class="line">	struct cam_buffer</span><br><span class="line">	&#123;</span><br><span class="line">		void* start;</span><br><span class="line">		unsigned int length;</span><br><span class="line">	&#125;;</span><br><span class="line">	char *devName;</span><br><span class="line">	int widthCap;</span><br><span class="line">	int heightCap;</span><br><span class="line">	int width;</span><br><span class="line">	int height;</span><br><span class="line">	int fd_cam;</span><br><span class="line">	cam_buffer *buffers;</span><br><span class="line">	unsigned int n_buffers;</span><br><span class="line">	int frameIndex;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">#endif /* V4L2CAP_H_ */</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line">/*</span><br><span class="line"> * main.cpp</span><br><span class="line"> *</span><br><span class="line"> *  Created on: Jul 26, 2017</span><br><span class="line"> *      Author: wordzzzz</span><br><span class="line"> */</span><br><span class="line"></span><br><span class="line">#include &quot;include.h&quot;</span><br><span class="line">#include &quot;v4l2cap.h&quot;</span><br><span class="line"></span><br><span class="line">#define IMAGEWIDTH 640</span><br><span class="line">#define IMAGEHEIGHT 480</span><br><span class="line"></span><br><span class="line">#define TRUE 1</span><br><span class="line">#define FALSE 0</span><br><span class="line"></span><br><span class="line">int main()</span><br><span class="line">&#123;</span><br><span class="line">	IplImage* img,* img_cap;</span><br><span class="line">	CvMat cvmat,cvmat_cap;</span><br><span class="line">	double t;</span><br><span class="line">	unsigned char *frame = NULL;</span><br><span class="line">	unsigned long frameSize = 0;</span><br><span class="line">	string videoDev=&quot;/dev/video1&quot;;</span><br><span class="line"></span><br><span class="line">	V4L2Capture *vcap = new V4L2Capture(const_cast&lt;char*&gt;(videoDev.c_str()),</span><br><span class="line">			IMAGEWIDTH, IMAGEHEIGHT, IMAGEWIDTH_CAP, IMAGEHEIGHT_CAP);</span><br><span class="line">	vcap-&gt;preBegin();                                //预览模式开启</span><br><span class="line"></span><br><span class="line">	cvNamedWindow(&quot;one&quot;,CV_WINDOW_AUTOSIZE);         //创建显示窗口</span><br><span class="line"></span><br><span class="line">	while(1)&#123;</span><br><span class="line">		t = (double)cvGetTickCount();</span><br><span class="line">		vcap-&gt;getFrame((void **) &amp;frame, &amp;frameSize);//获取图像队列</span><br><span class="line">		cvmat = cvMat(IMAGEHEIGHT,IMAGEWIDTH,CV_8UC3,frame);//CV_8UC3</span><br><span class="line">		img = cvDecodeImage(&amp;cvmat,1);               //OpenCV解码</span><br><span class="line">		if(!img)    printf(&quot;No img\n&quot;);</span><br><span class="line">		cvShowImage(&quot;one&quot;,img);                      //显示图像</span><br><span class="line">		cvReleaseImage(&amp;img);                        //循环外释放也可以</span><br><span class="line">		vcap-&gt;backFrame();                           //返回图像队列</span><br><span class="line">        cvWaitKey(1);                                //不写这句话将无法显示图像</span><br><span class="line">		t=(double)cvGetTickCount()-t;</span><br><span class="line">		printf(&quot;used time is %gms\n&quot;,(t/(cvGetTickFrequency()*1000)));</span><br><span class="line">	&#125;</span><br><span class="line">	vcap-&gt;preEnd();                                  //预览结束</span><br><span class="line"></span><br><span class="line">	return 0;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong><font color="red" size="3" face="仿宋">系列教程持续发布中，欢迎订阅、关注、收藏、评论、点赞哦～～(￣▽￣～)～</font></strong></p>
<p><strong><font color="red" size="3" face="仿宋">完的汪(∪｡∪)｡｡｡zzz</font></strong></p>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Word Zzzz
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://wordzzzz.gitee.io/2017/10/09/tx-9/" title="NVIDIA Jetson TX1 系列开发教程之九：USB摄像头MJPEG格式图像采集">http://wordzzzz.gitee.io/2017/10/09/tx-9/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/TX1/" rel="tag"># TX1</a>
          
            <a href="/tags/USB摄像头/" rel="tag"># USB摄像头</a>
          
            <a href="/tags/MJPEG/" rel="tag"># MJPEG</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/10/08/tx-8/" rel="next" title="NVIDIA Jetson TX1 系列开发教程之八：Qt安装与配置">
                <i class="fa fa-chevron-left"></i> NVIDIA Jetson TX1 系列开发教程之八：Qt安装与配置
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/10/10/tx-10/" rel="prev" title="NVIDIA Jetson TX1 系列开发教程之十：V4L2+OpenCV2.4.13实现预览、拍照功能">
                NVIDIA Jetson TX1 系列开发教程之十：V4L2+OpenCV2.4.13实现预览、拍照功能 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zMjgzNi85Mzk3"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="Word Zzzz" />
            
              <p class="site-author-name" itemprop="name">Word Zzzz</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

			<!--my custom code begin-->
			<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
			<script src="https://cdnjs.cloudflare.com/ajax/libs/velocity/1.5.0/velocity.min.js"></script>
			<script type="text/javascript">
			  $("#sidebar").hover(function(){
				$("#mydivshow").velocity('stop').velocity({opacity: 1});
			  },function(){
				$("#mydivshow").velocity('stop').velocity({opacity: 0});
			  });
			</script>
			<div id="mydivshow" class="mydivshow">
			<!--my custom code end-->
			
          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">155</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">80</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/wordzzzz" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://gitee.com/wordzzzz" target="_blank" title="Gitee">
                    
                      <i class="fa fa-fw fa-glide"></i>Gitee</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:wordzzzzgm@gmail.com" target="_blank" title="E-Mail">
                    
                      <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://plus.google.com/" target="_blank" title="Google">
                    
                      <i class="fa fa-fw fa-google"></i>Google</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.weibo.com/u/3191972527?from=107C295010&wm=20005_0002&sourceType=weixin&uid=3191972527&is_all=1" target="_blank" title="微博">
                    
                      <i class="fa fa-fw fa-weibo"></i>微博</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/wordzzzz" target="_blank" title="知乎">
                    
                      <i class="fa fa-fw fa-bell"></i>知乎</a>
                </span>
              
            
          </div>

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://blog.csdn.net/u011475210" title="CSDN博客主页" target="_blank">CSDN博客主页</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://wordzzzz.gitee.io" title="中国站主页" target="_blank">中国站主页</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://wordzzzz.github.io" title="全球站主页" target="_blank">全球站主页</a>
                  </li>
                
              </ul>
            </div>
          

          <div id="player1" class="aplayer"></div>
<script src="/js/src/APlayer.min.js"></script>
<script type="text/javascript">
var ap = new APlayer({
    element: document.getElementById('player1'),                       // Optional, player element
    narrow: false,                                                     // Optional, narrow style
    autoplay: false,                                                    // Optional, autoplay song(s), not supported by mobile browsers
    showlrc: 0,                                                        // Optional, show lrc, can be 0, 1, 2, see: ###With lrc
    mutex: true,                                                       // Optional, pause other players when this player playing
    theme: '#e6d0b2',                                                  // Optional, theme color, default: #b7daff
    mode: 'random',                                                    // Optional, play mode, can be `random` `single` `circulation`(loop) `order`(no loop), default: `circulation`
    preload: 'metadata',                                               // Optional, the way to load music, can be 'none' 'metadata' 'auto', default: 'auto'
    listmaxheight: '513px',                                             // Optional, max height of play list
    music: {                                                           // Required, music info, see: ###With playlist
        title: '你曾是少年',                                          // Required, music title
        author: 'cover',                          // Required, music author
        url: 'http://mp3.qqmusic.cc/yq/102426570.mp3',  // Required, music url
        pic: '/images/visitor.jpg',  // Optional, music picture
    }
});
</script>
        </div>
		<!--my custom code begin-->
		</div>
		<!--my custom code end-->
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2017 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Word Zzzz</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">176.8k</span>
  
</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>




  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('-1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("tnjOBN3eibs4dfP2s8dFMF8s-gzGzoHsz", "tDaBF4vRsSyaeSk9vKOOow6E");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "box";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
  </script>

  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>


  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.3"></script>


  <script src="/js/src/Aplayer-Controler.js"></script>
<div id="AP-controler"></div>
<script type="text/javascript">
var myapc=new APlayer_Controler({
		APC_dom:$('#AP-controler'),
		aplayer:ap, //此为绑定的aplayer对象
		attach_right:false,
		position:{top:'300px',bottom:''},
		fixed:true,
		btn_width:100,
		btn_height:120,
		img_src:['http://oty1v077k.bkt.clouddn.com/bukagirl.jpg',
				'http://oty1v077k.bkt.clouddn.com/jumpgirl.jpg',
				'http://oty1v077k.bkt.clouddn.com/pentigirl.jpg',
				'http://oty1v077k.bkt.clouddn.com/%E8%90%8C1.gif'],
		img_style:{repeat:'no-repeat',position:'center',size:'contain'},
		ctrls_color:'rgba(173,255,47,0.8)',
		ctrls_hover_color:'rgba(255,140,0,0.7)',
		tips_on:true,
		tips_width:140,
		tips_height:25,
		tips_color:'rgba(255,255,255,0.6)',
		tips_content:{},
		timeout:30
	});
</script>

<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>



</body>
</html>
